package org.jtb.quickr;

import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.commons.httpclient.methods.multipart.Part;

class UploadRequest extends SignedRequest {
    private static Logger logger = Logger.getLogger(UploadRequest.class.getName());
    
    private UploadCriteria photoUpload;
    
    protected UploadRequest(String baseUrl, String apiKey, String secret, AuthResponse.Token authToken, UploadCriteria photoUpload) {
        super(baseUrl, apiKey, secret, authToken);
        
        this.photoUpload = photoUpload;
    }
    
    protected Map<String,String> getArgs() {
        String title = photoUpload.getTitle();        
        if (photoUpload.getTitle() != null) {
            putArg("title", title);
        }
        String description = photoUpload.getDescription();
        if (description != null) {
            putArg("description", description);
        }
        Set<String> tags = photoUpload.getTags();
        if (tags != null && tags.size() > 0) {
            putArg("tags", join(tags, ' '));
        }
        Boolean publicPhoto = photoUpload.getPublicPhoto();
        if (publicPhoto != null) {
            putArg("is_public", new BooleanInt(publicPhoto).toString());
        }
        Boolean friendPhoto = photoUpload.getFriendPhoto();
        if (friendPhoto != null) {
            putArg("is_friend", new BooleanInt(friendPhoto).toString());
        }
        Boolean familyPhoto = photoUpload.getFamilyPhoto();
        if (familyPhoto != null) {
            putArg("is_family", new BooleanInt(familyPhoto).toString());
        }
        
        return super.getArgs();
    }
    
    public PhotoIdResponse execute() throws QuickrException {
        FlickrUrl furl = new PostUrl(getBaseUrl(), getArgs(), getApiKey(), getSecret(), getAuthToken());
        Map<String,String> args = furl.getArgs();
        Map<String,Object> data = new HashMap<String,Object>(args);
        data.put("photo", photoUpload.getPhoto());
        
        HttpVerb post = new MultipartPost(furl.getUrl(), data);
        InputStream is = post.execute();
        
        PhotoIdResponse pid = new PhotoIdResponse(is);
        return pid;
    }    
}
